package com.cai.util;

import com.cai.pojo.Mail;

import javax.mail.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author RuoLi
 * QQ邮箱 发送账号 找回账号密码
 * 导入javax.mail.*的包
 */
public class MailUtil {
    static InputStream is = C3p0Util.class.getClassLoader().getResourceAsStream("mail.properties");
    static Properties props = new Properties();
    public static void sendMail(Mail mail){
        try {
            props.load(is);
            //构建授权信息 进行SMTP身份验证
            Authenticator authenticator=new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    String sendUser =props.getProperty("mail.SendUser");
                    String sendPassword=props.getProperty("mail.SendPassword");
                    return new PasswordAuthentication(sendUser,sendPassword);
                }
            };
            //使用环境属性和授权信息 创建邮件会话
            Session mailSession=Session.getInstance(props,authenticator);
            //创建邮件消息
            MimeMessage mimeMessage=new MimeMessage(mailSession);
            //设置发送人 发送人默认
            InternetAddress from=new InternetAddress(props.getProperty("mail.SendUser"));
            mimeMessage.setFrom(from);
            //设置收件人
            InternetAddress to= new InternetAddress(mail.getReceiptUser());
            mimeMessage.setRecipient(RecipientType.TO,to);
            //邮件标题
            mimeMessage.setSubject(mail.getSendSubject());
            //邮件内容体
            mimeMessage.setContent(mail.getSendContent(),"text/html;charset=UTF-8");
            //发送邮件
            Transport.send(mimeMessage);
        } catch (IOException | MessagingException e) {
            e.printStackTrace();
        }
    }
}
